export function debounce(executor, time) {
  let timer = null
  return function () {
    let param = arguments // 储存参数
    clearTimeout(timer) // 清除定时器
    timer = setTimeout(() => {
      executor.call(this, param[0])
    }, time)
  }
}

export const AJAX = {
  get(url, hearder) {
    let xhr = null
    if (XMLHttpRequest) {
      xhr = new XMLHttpRequest()
    } else {
      xhr = new ActiveXObject('Microsoft.XMLHTTP')
    }
    return new Promise((resolve, reject) => {
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            if (xhr.responseText) {
              resolve(xhr.responseText)
            }
          } else {
            reject(xhr.status);
          }
        }
      }
      xhr.open('GET', url);
      if (hearder) {
        hearder.forEach((element, index) => {
          xhr.setRequestHeader(index, element)
        })
      }
      xhr.send()
    })
  },
  post(url, data, hearder) {
    let xhr;
    if (XMLHttpRequest) {
      xhr = new XMLHttpRequest()
    } else {
      xhr = new ActiveXObject('Microsoft.XMLHTTP')
    }
    // 3.创建并返回 Promise 对象
    return new Promise((resolve, reject) => {
      // 4.监听请求变化
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            if (xhr.responseText) {  // 防止复杂请求请求两次
              resolve(xhr.responseText)
            }
          } else {
            reject(xhr.status)
          }
        }
      }
      // 5.发送请求
      xhr.open('POST', url);
      // 设置 body 是 json 字符串格式
      xhr.setRequestHeader('Content-Type', 'application/json')
      if (hearder) {
        hearder.forEach((element, index) => {
          xhr.setRequestHeader(index, element)
        })
      }
      if (data) {
        xhr.send(JSON.stringify(data));
      } else {
        xhr.send()
      }
    });
  }
}